package com.whacos.modules.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.enums.Constant;
import com.whacos.common.enums.DelFlagEnum;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.oa.entity.Notify;
import com.whacos.modules.oa.dto.NotifyDTO;
import com.whacos.modules.oa.entity.NotifyRecord;
import com.whacos.modules.oa.service.NotifyRecordService;
import com.whacos.modules.oa.service.NotifyService;
import com.whacos.modules.oa.vo.NotifyRecordVO;
import com.whacos.modules.oa.vo.NotifyVO;
import com.whacos.modules.system.entity.Dict;
import com.whacos.modules.system.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author xiongdun
 * @description 通知通告
 * @since 2018/11/17 17:11
 */
@Controller
@RequestMapping("/oa/notify")
@Slf4j
public class NotifyController extends BaseController {

    @Autowired
    private NotifyService notifyService;
    @Autowired
    private NotifyRecordService notifyRecordService;
    @Autowired
    private DictService dictService;

    // @Log(value = "跳转到消息通知页面")
    @GetMapping()
    @RequiresPermissions("oa:notify:notify")
    public String oaNotify() {
        return "oa/notify/notify";
    }

    // @Log(value = "查询消息通知列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("oa:notify:notify")
    public IPage<NotifyVO> list(NotifyVO notifyVO) {
        // 查询列表数据
        IPage<NotifyVO> notifyVOPage = new Page<>();
        try {
            Notify notify = new Notify();
            BeanUtils.copyProperties(notifyVO, notify);
            IPage<Notify> notifyPage = notifyService.page(new Page<>(notifyVO.getPageNum(), notifyVO.getPageSize()),
                    new LambdaQueryWrapper<Notify>()
                            .eq(StringUtils.isNotEmpty(notify.getType()), Notify::getType, notify.getType())
                            .eq(StringUtils.isNotEmpty(notify.getTitle()), Notify::getTitle, notify.getTitle())
                            .eq(StringUtils.isNotEmpty(notify.getStatus()), Notify::getStatus, notify.getStatus())
                            .orderByDesc(Notify::getCreatedDate));
            BeanUtils.copyPage(notifyPage, notifyVOPage);
        } catch (Exception e) {
            log.error("查询消息通知列表异常，异常原因：" + e.getMessage(), e);
        }
        return notifyVOPage;
    }

    // @Log(value = "跳转到新增消息通知")
    @GetMapping("/add")
    @RequiresPermissions("oa:notify:add")
    public String add() {
        return "oa/notify/add";
    }

    // @Log(value = "跳转到编辑消息通知")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("oa:notify:edit")
    public String edit(@PathVariable("id") Long id, Model model) {
        Notify notify = notifyService.getById(id);
        List<Dict> oaNotifyTypes = dictService.listByType("oa_notify_type");
        /*String type = notify.getType();
        for (SysDictVO sysDict : dictDOS) {
            if (type.equals(sysDict.getValue())) {
                sysDict.setRemarks("checked");
            }
        }*/

        oaNotifyTypes.forEach(sysDict -> {
            if (notify.getType().equals(sysDict.getValue())) {
                sysDict.setRemark("checked");
            }
        });
        model.addAttribute("oaNotifyTypes", oaNotifyTypes);
        model.addAttribute("notify", notify);
        return "oa/notify/edit";
    }

    @Log(value = "保存消息通知")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("oa:notify:add")
    public ResponseVO save(NotifyVO notifyVO) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Notify notify = new Notify();
            BeanUtils.copyProperties(notifyVO, notify);
            notify.createdData(this.getUserId());
            notify.setDelFlag(DelFlagEnum.NORMAL.getValue());
            if (notifyService.save(notify)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log(value = "修改消息通知")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("oa:notify:edit")
    public ResponseVO update(NotifyVO notifyVO) {
        if (Constant.DEMO_ACCOUNT.equals(getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Notify notify = new Notify();
            BeanUtils.copyProperties(notifyVO, notify);
            notify.updatedData(this.getUserId());
            if (notifyService.updateById(notify)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log(value = "删除消息通知")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("oa:notify:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            Notify notify = new Notify();
            notify.setId(id);
            notify.setDelFlag(DelFlagEnum.DELETE.getValue());
            notify.updatedData(this.getUserId());
            if (notifyService.updateById(notify)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log(value = "批量删除消息通知")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("oa:notify:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (notifyService.batchRemove(ids)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    // @Log(value = "查询当前用户前3条消息")
    @ResponseBody
    @GetMapping("/message")
    public IPage<NotifyVO> message() {
        // 请求参数
        NotifyRecord notifyRecord = new NotifyRecord();
        notifyRecord.setUserId(this.getUserId());
        notifyRecord.setIsRead(Integer.parseInt(Constant.OA_NOTIFY_READ_NO));
        IPage<NotifyVO> notifyVOPage = new Page<>();
        try {
            IPage<NotifyDTO> notifyDTOPage = notifyService.selfList(new Page<>(0, 3), notifyRecord);
            BeanUtils.copyPage(notifyDTOPage, notifyVOPage);
        } catch (Exception e) {
            log.error("查询通知消息异常，异常原因：" + e.getMessage(), e);
        }
        return notifyVOPage;
    }

    // @Log(value = "跳转到当前用户消息页面")
    @GetMapping("/selfNotify")
    public String selfNotify() {
        return "oa/notify/selfNotify";
    }

    // @Log(value = "查询当前用户消息")
    @ResponseBody
    @GetMapping("/selfList")
    public IPage<NotifyVO> selfList(NotifyRecordVO notifyRecordVO) {
        IPage<NotifyVO> notifyVOPage = new Page<>();
        try {
            // 请求参数
            NotifyRecord notifyRecord = new NotifyRecord();
            BeanUtils.copyProperties(notifyRecordVO, notifyRecord);
            notifyRecord.setUserId(this.getUserId());
            // 查询数据
            IPage<NotifyDTO> notifyDTOPage = notifyService.selfList(new Page<>(notifyRecordVO.getPageNum(),
                    notifyRecordVO.getPageSize()), notifyRecord);
            // 返回结果
            BeanUtils.copyPage(notifyDTOPage, notifyVOPage);
        } catch (Exception e) {
            log.error("查询通知消息异常，异常原因：" + e.getMessage(), e);
        }
        return notifyVOPage;
    }

    // @Log(value = "当前用户阅读消息，并修改阅读状态")
    @GetMapping("/read/{id}")
    @RequiresPermissions("oa:notify:edit")
    public String read(@PathVariable("id") Long id, Model model) {
        Notify notify = notifyService.getById(id);
        //更改阅读状态
        notifyRecordService.changeRead(id);
        model.addAttribute("notify", notify);
        return "oa/notify/read";
    }

    // @Log(value = "当前用户阅读消息，并修改阅读状态")
    @PostMapping("/batchRead")
    @RequiresPermissions("oa:notify:edit")
    public ResponseVO batchRead(@RequestParam("ids[]") List<Long> ids) {
        // 批量更改阅读状态
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            this.notifyRecordService.batchChangeRead(ids);
        } catch (Exception e) {
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }
}
